<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Channel\ElmWaiMai;
use App\Kuafu\WaiMai\Channel\MtWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class WaiMaiOrderRepairV2 extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'waiMai-orderRepairV2 {shopId?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '外卖订单自动修复补单V2';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        $argShopId = (int)$this->argument('shopId');

        $date = date('Ymd');

        WaiMaiShopMappingModel
            ::query()
            ->when($argShopId, function ($query) use ($argShopId) {
                $query->where('shopId', $argShopId);
            })
            ->chunk(500, function ($shops) use ($date) {
                $shops->each(function ($shop) use ($date) {

                    $shopId      = $shop->shopId;
                    $sourceType  = $shop->sourceType;
                    $thirdShopId = $shop->thirdShopId;

                    $serialNums = WaiMaiOrderModel::suffix($shopId)
                                                  ->where('createdAt', '>=', strtotime($date))
                                                  ->where('shopId', $shopId)
                                                  ->where('sourceType', $sourceType)
                                                  ->orderByDesc('serialNum')->pluck('serialNum');
                    if (!$serialNums->count()) {
                        return;
                    }

                    // 判断serialNums的值是否连续，如果不是的话找出缺少的值
                    $serialNums = $serialNums->toArray();

                    $missings = $this->missing_numbers($serialNums);
                    if ($missings) {
                        dump($shopId . '-' . $sourceType, $missings);

                        foreach ($missings as $serialNum) {

                            if ($sourceType == 3) {
                                $orderId = (new MtWaiMai($thirdShopId,
                                    $shopId))->getOrderIdByDaySeq($date,
                                    $serialNum)['data']['orderId'] ?? 0;
                                if (!$orderId) {
                                    continue;
                                }
                                BaseWaiMaiOrderService::getIns($sourceType)
                                                      ->repairOrder($shopId, $orderId);
                            } else {

                                $data = collect(ElmWaiMai::getIns($sourceType, $shopId, $thirdShopId)
                                                         ->getAllOrders(1, 50,
                                                             $date)['oriData']['list'])->keyBy('daySn');

                                $order = $data[$serialNum] ?? [];
                                if (!$order) {
                                    continue;
                                }

                                BaseWaiMaiOrderService::getIns($sourceType)
                                                      ->repairOrder($shopId, $order['id']);
                            }
                        }
                    }
                });
            });

    }


    private function missing_numbers($array)
    {
        sort($array);  // 对数组进行排序
        $missing = [];  // 用于存放缺失的数字
        for ($i = 0; $i < count($array) - 1; $i++) {
            if ($array[$i] + 1 != $array[$i + 1]) {
                for ($j = $array[$i] + 1; $j < $array[$i + 1]; $j++) {
                    $missing[] = $j;  // 将缺失的数字加入到array中
                }
            }
        }
        return $missing;  // 返回缺失的数字
    }
}
